const express = require("express")
const app = express();
const path = require("path");

//处理body请求体的中间件
app.use(express.urlencoded())
app.use(express.json())
//定义一个延迟响应的请求接口
app.get('/userLazy',(req,res)=>{
    setTimeout(() => {
        const token = req.headers.token;
        if(!token){
           
            return  res.send({
                code: 10002,
                msg: "没有权限",
                data: null
            })
            
        }
        const {userId} =req.query;
          //如果查询失败
    if (userId !== "001") {
        return res.send({
          code: 10001,
          msg: "查询失败",
          data: null
        })
      }
  
  
      //查询成功 响应
      res.send({
        code: 10000,
        msg: "查询成功",
        data: {
          name: "李博",
          age: 18,
          sex: "男"
        }
      })
        
    }, 3000);
})
//查询学生信息接口
app.get("/user", (req, res) => {
  // console.log(req.query);
  const {
    userId
  } = req.query;


  //如果查询失败
  if (userId !== "001") {
    return res.send({
      code: 10001,
      msg: "查询失败",
      data: null
    })
  }


  //查询成功 响应
  res.send({
    code: 10000,
    msg: "查询成功",
    data: {
      name: "李博",
      age: 18,
      sex: "男"
    }
  })

})

app.get("/userInfo", (req, res) => {
  console.log(req.query, "req.query");
  const {
    userId
  } = req.query;


  //如果查询失败
  if (userId !== "001") {
    return res.send({
      code: 10001,
      msg: "查询失败",
      data: null
    })
  }


  //查询成功 响应
  res.send({
    code: 10000,
    msg: "查询成功",
    data: {
      name: "李博",
      age: 18,
      sex: "男"
    }
  })
})

app.post("/adduser", (req, res) => {
  console.log("adduser");
  console.log(req.body, "req.body");
  console.log(req.query, "req.query");
  const {
    name,
    age,
    sex
  } = req.body;

  if (!name || !age || !sex) {
    return res.send({
      code: 10001,
      mes: "添加失败",
      data: null
    })
  }

  res.send({
    code: 10000,
    mes: "添加成功",
    data: null
  })
})


//静态资源部署接口
app.get("/1", (req, res) => {
  const filePath = path.resolve(__dirname, "./01.创建请求拦截器.html");
  res.sendFile(filePath);
})
app.get("/2", (req, res) => {
    const filePath = path.resolve(__dirname, "./02.设置响应拦截器.html");
    res.sendFile(filePath);
  })
  app.get("/3", (req, res) => {
    const filePath = path.resolve(__dirname, "./03.创建axios实例.html");
    res.sendFile(filePath);
  })
  app.get("/4", (req, res) => {
    const filePath = path.resolve(__dirname, "./04.拦截器练习.html");
    res.sendFile(filePath);
  })
  app.get("/5", (req, res) => {
    const filePath = path.resolve(__dirname, "./05.取消请求练习.html");
    res.sendFile(filePath);
  })
 
 
 
app.listen(3030, () => {
  console.log("服务器请求成功 请访问 http://127.0.0.1:3030");
})